package com.cn.applet.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * Redis Client
 *
 * @author  daizhengtao
 * @date 2018-09-24
 * */
@Component
public class RedisClient {

    private Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName());

    @Autowired
    private JedisPool jedisPool;

    public void set(String key, String value){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.set(key, value);
        } catch(Exception e){
            logger.info("缓存服务器连接失败！" + e.getMessage());
        }finally {
            //返还到连接池
            closeJedis(jedis);
        }
    }

    public String get(String key){
        String value = "";
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            value = jedis.get(key);
        } catch(Exception e){
            logger.info("缓存服务器连接异常！"+ e.getMessage());
        }finally {
            closeJedis(jedis);
        }
        return value;
    }

    private void closeJedis(Jedis jedis){
        if (null != jedis){
            jedis.close();
        }
    }
}
